package com.csdj.springboottest.interceptors;

import com.csdj.springboottest.common.CommonConstant;
import com.csdj.springboottest.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * author:cloud
 * date:2021/4/23 0023
 **/

public class LoginInteceptor implements HandlerInterceptor {

    private RedisService redisService;

    private Logger log = LoggerFactory.getLogger("interceptor");

    public LoginInteceptor(RedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //实现拦截代码
        logParam(request);
        if(checkFromCookie(request))return true;
        log.info("登录验证失败");

        response.getHeaderNames().stream().forEach(head ->{
            log.info("header:{} value:{}",head,response.getHeader(head));
        });
        response.sendRedirect("/login");
        return false;
    }

    /**
     * 通过cookie来校验登录数据
     * @param request
     * @return
     */
    private boolean checkFromCookie(HttpServletRequest request){
        //用来保存cookie中的uid和token
        String cuid = "";
        String ctoken = "";
        Cookie[] cookies = request.getCookies();
        if(cookies == null || cookies.length < 2){
            return false;
        }
        for(Cookie cookie : cookies){
            if(cookie.getName().equals(CommonConstant.COOKIE_UID)){
                cuid = cookie.getValue();
            }
            if(cookie.getName().equals(CommonConstant.COOKIE_TOKEN)){
                ctoken = cookie.getValue();
            }
        }
        if(StringUtils.isEmpty(cuid) || StringUtils.isEmpty(ctoken)){
            //uid 或是token 不存在
            return false;
        }
        //将token与redis中保存的token进行对比
//        Object obj = redisService.get(CommonConstant.CACHE_TOKEN_PREFIX+cuid);
//        if(obj != null){
//            String cacheToken = obj.toString();
//            if(cacheToken.equals(ctoken)){
//                return true;
//            }
//        }
        String cacheToken = redisService.getString(CommonConstant.CACHE_TOKEN_PREFIX+cuid);
        if(ctoken.equals(cacheToken)){
            return true;
        }
        return false;
    }


    /**
     * 打印http请求参数
     * @param request
     */
    private void logParam(HttpServletRequest request){
        final Enumeration<String> names = request.getParameterNames();
        StringBuilder sb = new StringBuilder();
        sb.append("url:").append(request.getRequestURI()).append("  ");
        if(names != null && names.hasMoreElements()){
            while (names.hasMoreElements()){
                String name = names.nextElement();
                String param = request.getParameter(name);
                sb.append(name).append("=").append(param).append("  ");
            }
        }
        log.info(sb.toString());
    }
}
